package core;

import java.io.Serializable;


/**
 * An OutPort is a port which can yield a value.
 * Optionally, it has a DispatcherPort which sends triggers
 * whenever the OutPort value changes.
 * 
 * @author Wijnand
 */
public abstract class OutPort implements ValuePort, Serializable {
	Class valueClass;
	DispatcherPort valueChanged;
    private InPort requestPort;

	public OutPort(Class valueClass) {
		this(valueClass, null);
	}

	public OutPort(Class valueClass, DispatcherPort valueChanged) {
		this.valueClass = valueClass;
		this.valueChanged = valueChanged;
	}

	public Class getValueClass() { return valueClass; }

	/**
	 * @return associated DispatcherPort which sends "value changed" triggers when the
	 * value of this OutPort is changed, or null if no such DispatcherPort is available.
	 * If the return-value is not null, then every implementation should
	 * guarantee to send "value changed" triggers whenever its value changes
	 * (that is whenever getValue() will yield a different value). However,
	 * if the value changes more than once without a getValue()-call, then the
	 * trigger must be sent only once. Also, it is permissible for an implementation
	 * to send a trigger even if the value didn't actually change.
	 */
	public DispatcherPort getValueChangedPort() {
		return valueChanged;
	}

	public void setValueChangedPort(DispatcherPort dp) {
		this.valueChanged = dp;
	}

	/**
	 * @return the current value of this OutPort.
	 */
	public final Object getValue()
	{
		Tracker.getInstance().valueRequested(this);
		Object obj = getValueInternal();
		Tracker.getInstance().valueDispatched(this, obj);
		return obj;
	}

	protected abstract Object getValueInternal();

    public void setRequestPort(InPort requestPort) {
        this.requestPort = requestPort;
    }

    public InPort getRequestPort(){
        return requestPort;
    }
}

